#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$

import socket
from basic_types import *


# Constants
SERVER_PORT = 9450

    
def directRPCClient( message, ip="localhost", port=SERVER_PORT ):
    # this doesn't actually belong here, but it's handy to have it... [EF]
    message = message + "\n"
    sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    sock.connect( (ip, port) )
    sock.send( message )
    response = ""
    # caveat: data must fit into memory!
    while True:
        data = sock.recv( 1024 )
        if not data:
            break
        response = response + data
    sock.close()
    #print("Received: %s" % response)

    from basic_types.factory import Factory
    for imp in Factory.import_all():
        try:
            exec imp
        except Exception, e:
            print "exec failed", imp, e

    try:
        output = eval( response )
    except Exception, e:
        print "Exception when evaluating response to direct rpc:", e
        print "Response:", response
        return None
    return output

if __name__ == "__main__":
    import sys
    if len( sys.argv ) > 2:
        ip = sys.argv[1]
        port = SERVER_PORT
        if ":" in ip:
            ip, port = ip.split(":")
        message = " ".join( sys.argv[2:] )
        print directRPCClient( message , ip=ip, port=int( port ) )

